<!-- 模板，div ，el ui元素布局-->
<template>
  <!-- 一个根DIV -->
  <div>
    <!-- 1.导航条 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>博客管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加博客</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 2.卡片视图 -->
    <el-card>
      <!-- 提示区域  el-alert -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>

      <!-- el-steps 步骤条区域，引导作用  :active 当前区域 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="博客图片"></el-step>
        <el-step title="博客内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- el-tabs 切换页、el-tab-pane  v-model="activeIndex"  当前切换值 -->
        <el-tabs v-model="activeIndex" :tab-position="'left'">
          <!-- 第一个tab页 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="标题" prop="title">
              <el-input v-model="addForm.title"></el-input>
            </el-form-item>
            <el-form-item label="摘要" prop="description">
              <el-input v-model="addForm.description"></el-input>
            </el-form-item>

            <!-- 博客分类 -->
            <el-form-item label="分类" prop="cId">
              <!-- 级联选择器
          options	可选项数据源，键名可通过 Props 属性配置
          :props
           v-model="selectedKeys"：存储选择的数据
            @change 当选中节点变化时触发
           -->
              <el-cascader
                expand-trigger="hover"
                :options="parentCateList"
                :props="cascaderProps"
                v-model="selectedKeys"
                @change="parentCateChanged"
                clearable
                change-on-select
              >
              </el-cascader>
            </el-form-item>

            <!-- 首页大图 -->
            <el-form-item label="大图" prop="img">
              <!-- 上传大图 -->
              <el-upload
                class="avatar-uploader"
                :action="action"
                :show-file-list="false"
                :on-change="handleChange"
                :auto-upload="false"
                accept=".jpg,.jpeg,.png,.gif"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="addForm.img" :src="addForm.img" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-tab-pane>

          <!--第二个tab页  多图上传 el-upload  一挂多 图片表 -->
          <el-tab-pane label="博客图片" name="1">
            <!-- action 表示图片要上传到的后台API地址 ，上传图片  on-钩子函数  headers：设置上传的请求头部，list-type 文件列表的类型 picture-card图片墙-->

            <el-upload
               multiple  
              :action="action"
              list-type="picture-card"
              :auto-upload="false"
              accept=".jpg,.jpeg,.png,.gif"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="handleMultChange"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-tab-pane>

          <!-- 第三个tab页 quill-editor 富文本框 带着文本格式保存 -->
          <el-tab-pane label="博客内容" name="2">
            <!-- 富文本编辑器组件 addForm.content 字符串 ，
            存入到数据库是格式文本，注意数据库字段格式 longtext
            图片会被存成 编码data:image/jpeg;base64,
            -->
            <el-form-item label="内容" prop="content">
              <quill-editor v-model="addForm.content"></quill-editor>
            </el-form-item>
            <div style="text-align: center">
              <!-- 添加按钮 -->
              <el-button type="primary" class="btnAdd" @click="add"
                >添加博客</el-button
              >
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 3.弹框区域 -->
  </div>
</template>

<!-- 行为，业务逻辑 -->
<script>
export default {
  //变量，配合ElementUI使用
  data() {
    return {
      ////////////////////////////////上传图片
      action: this.$store.state.baseURL + "/blog/save",
      file: "", //大图
      filelist: [], //多图

      dialogImageUrl: "",
      dialogVisible: false,

      //分类相关
      parentCateList: [], //后台传来的树形结构数据
      cascaderProps: {
        //配置怎么解析后台返来的数据
        label: "cname",
        value: "id",
        children: "children",
      },
      selectedKeys: "", //路径

      activeIndex: "0",
      /// ////////////////////添加框  form，验证
      addDialogVisible: false,
      addForm: {
        title: "",
        description: "",
        content: "",
        img: "",
        cId: "",
      },
      addFormRules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 3,
            max: 25,
            message: "长度在 3 到 25 个字符",
            trigger: "blur",
          },
        ],
        description: [
          { required: true, message: "请输入摘要", trigger: "blur" },
        ],
        content: [{ required: true, message: "请输入内容", trigger: "blur" }],
        cId: [{ required: true, message: "请选择分类", trigger: "blur" }],
        img: [{ required: true, message: "请上传图片", trigger: "blur" }],
      },
    };
  },
  //页面初始化加载，生命周期函数
  created() {
    //获取数据
    this.getCateList();
  },
  //自定义函数，操作变量
  methods: {
    //////////////////////////////上传图片

    ///////单图使用
    handleChange(file, fileList) {
      this.addForm.img = URL.createObjectURL(file.raw);
      console.log("file", file);
      this.file = file; //把文件赋给变量
    },

    //上传图片之前回调
    beforeAvatarUpload(file) {
      console.log("上传前：", file);
      const isJPG =
        file.type === "image/jpeg" || "image/png" || "image/jpg" || "image/gif";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    //////////多图使用
    handleRemove(file, fileList) {
      // this.filelist = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleMultChange(file, fileList) {
      this.filelist = fileList;
    },

    // 获取分类数据
    async getCateList() {
      const { data: res } = await this.$http.post("/category/list");
      if (res.code !== 200) {
        return this.$message.error("获取分类失败！" + res.msg);
      }
      // 把数据列表，赋值给
      this.parentCateList = res.data;
      this.$gs.getTreeData(this.parentCateList); //去除空children
    },

    //分类选择触发
    parentCateChanged() {
      console.log("---", this.selectedKeys);
      this.addForm.cId = this.selectedKeys[this.selectedKeys.length - 1];
      console.log("this.addForm.cId", this.addForm.cId);
    },

    // tab页切换触发，规则验证
    beforeTabLeave(activeName, oldActiveName) {
      console.log("即将离开的标签页名字是：" + oldActiveName);
      console.log("即将进入的标签页名字是：" + activeName);

      // 第一个tab页，
      // if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
      //   this.$message.error('请先选择商品分类！')
      //   return false // 不切换
      // }
    },

    ///添加博客内容，带着图片
    add() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;

        //声明form  一起送后台
        let fd = new FormData();
        fd.append("file", this.file.raw); // 文件  ?file=xxx     file
        fd.append("blog", JSON.stringify(this.addForm)); //表单数据   ?user=xxxx  user
        let filelistraw=new Array()
        for(let item of this.filelist){
             fd.append("filelist",item.raw)
        }

        
        
       
        //打印fd
        fd.forEach((value, key) => {
          console.log("key %s: value %s", key, value);
        });

        // 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post("/blog/save", fd);

        if (res.code !== 200) {
          return this.$message.error("添加信息失败！" + res.msg);
        }

        this.$message.success("添加信息成功！");

        this.$router.push("/blog"); //跳转到列表页  this.$router、this.$store
      });
    },

    /// ////////////////////编辑功能
    async showEditDialog(id) {
      console.log(id);
      const { data: res } = await this.$http.get("/blog/info/" + id);
      if (res.code !== 200) {
        return this.$message.error("查询信息失败！" + res.msg);
      }
      console.log(res.data);
      this.editForm = res.data; // 对象复制
      this.editDialogVisible = true;
    },

    update() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        //
        const { data: res } = await this.$http.post(
          "/blog/update",
          this.editForm
        );
        if (res.code !== 200) {
          return this.$message.error("更新信息失败！" + res.msg);
        }

        // 提示修改成功
        this.$message.success("更新信息成功！");
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据列表
        this.getList();
      });
    },
  },
};
</script>

<!-- css,样式 ，scoped 本页CSS有效，生命同名class <el-card> ==> <div class="el-card">  -->
<style  scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.btnAdd {
  margin-top: 10px;
}
.el-steps {
  margin-bottom: 10px;
  margin-top: 10px;
}
</style>
